package com.zhisuo.apicenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhisuo.apicenter.model.ParkArea;
import com.zhisuo.apicenter.model.ParkAreaBuild;
import com.zhisuo.apicenter.model.RubbishOrder;
import com.zhisuo.apicenter.service.ApiService;
import com.zhisuo.apicenter.service.RubbishEventService;
import com.zhisuo.apicenter.service.UserManService;
import com.zhisuo.apicenter.util.DateUtil;
import com.zhisuo.apicenter.util.StringUtil;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 垃圾相关操作
 */
@Controller
@RequestMapping(value = "/rubbishevent")
public class RubbishEventController {

    private static final Logger log = LoggerFactory.getLogger(RubbishEventController.class);

    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }

    private RubbishEventService rubbishEventService;
    @Autowired
    public void setRubbishEventService(RubbishEventService rubbishEventService) {
        this.rubbishEventService = rubbishEventService;
    }
    private UserManService userManService;
    @Autowired
    public void setUserManService(UserManService userManService) {
        this.userManService = userManService;
    }

    /**
     * 垃圾收取员获取园区列表
     */
    @RequestMapping(value = "/getRubbishParkAreaList")
    public void getRubbishParkAreaList(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        List<ParkArea>  listParkArea=apiService.getListParkArea();
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "园区列表");
        resultObj.put("data", listParkArea);
        responseData(resultObj.toString(), resp);

    }

    /**
     * 垃圾收取员根据园区ID，获取园区预约列表
     */
    @RequestMapping(value = "/getRubbishOrderByAreaId")
    public void getRubbishOrderByAreaId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getRubbishOrderByAreaId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String parkareaid = jsonObject.getString("parkareaid");
        String nowdate= DateUtil.getDate()+" 01:00:00";
        List<RubbishOrder> listRubbishOrder=rubbishEventService.getRubbishOrderByParkAreaId(parkareaid,nowdate);

        if(listRubbishOrder != null && listRubbishOrder.size()>0){
            JSONArray jsonArray=new JSONArray();
            JSONObject jo=null;
            for(RubbishOrder order:listRubbishOrder){
                jo=new JSONObject();
                jo.put("buildname",order.getReceiptuserbuildname());
                jo.put("starttime",order.getReceiptuserorderstarttime());
                jo.put("endtime",order.getReceiptuserorderendtime());
                jsonArray.add(jo);
            }
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data",jsonArray);
            responseData(resultObj.toString(), resp);
            return;
        }else{
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "订单为空");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }
    }


    /**
     * 根据楼号ID判断园区是否存在垃圾车
     */
    @RequestMapping(value = "/getRubbishCarByBuildId")
    public void getRubbishCarByBuildId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getRubbishCarByBuildId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String buildid = jsonObject.getString("buildid");

        //根据BUILDID获取园区
        ParkAreaBuild userbuildinfo=userManService.getParkAreaBuildById(Integer.parseInt(buildid));




        if(userbuildinfo== null){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "园区不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        //根据园区ID获取车辆ID
        String carid=rubbishEventService.getCarIdByParkAreaId(userbuildinfo.getParkareaid());

        if(StringUtil.isEmpty(carid)){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "园区没有垃圾车");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "园区存在垃圾车");
        responseData(resultObj.toString(), resp);
    }



    /**
     * 用户预约收取垃圾
     */
    @RequestMapping(value = "/setRubbishOrderByUserId")
    public void setRubbishOrderByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setRubbishOrderByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String receiptuserid = jsonObject.getString("userid");
        String buildid = jsonObject.getString("buildid");
        String receiptuserorderstarttime = jsonObject.getString("receiptuserorderstarttime");
        String receiptuserorderendtime = jsonObject.getString("receiptuserorderendtime");

        //根据BUILDID获取园区
        ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(Integer.parseInt(buildid));

        if(buildinfo== null){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "园区不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        //根据园区ID获取车辆ID
        String carid=rubbishEventService.getCarIdByParkAreaId(buildinfo.getParkareaid());

        if(StringUtil.isEmpty(carid)){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "园区没有垃圾车");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        Integer boxid=0;
        String boxcode="0";


        rubbishEventService.insertNewRubbishOrder(receiptuserid,buildid,receiptuserorderstarttime,receiptuserorderendtime,carid,boxid,boxcode,buildinfo.getName(),buildinfo.getParkareaid(),buildinfo.getCode());

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "预约成功");
        responseData(resultObj.toString(), resp);
    }


    /**
     * 用户判断今天是否有预约，有，则返回预约记录，无，则返回时刻表
     */
    @RequestMapping(value = "/getHasRubbishOrderByUserId")
    public void getHasRubbishOrderByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getHasRubbishOrderByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");



        RubbishOrder rubbishOrder=rubbishEventService.getRubbishOrderByUserIdAndDay(userid);

        if(rubbishOrder==null){
            //根据USERID获取园区ID并获取时刻图

            String parkareabuildid=userManService.getParkAreaBuildIdByUserid(userid);

            if(StringUtil.isEmpty(parkareabuildid)){
                resultObj.put("error_code", 1);
                resultObj.put("error_msg", "用户没有设置园区");
                resultObj.put("data", "");
                responseData(resultObj.toString(), resp);
                return;
            }
            //根据BUILDID获取园区
            ParkAreaBuild userbuildinfo=userManService.getParkAreaBuildById(Integer.parseInt(parkareabuildid));
            if(userbuildinfo== null){
                resultObj.put("error_code", 1);
                resultObj.put("error_msg", "园区不存在");
                resultObj.put("data", "");
                responseData(resultObj.toString(), resp);
                return;
            }
            // userbuildinfo.getParkareaid()
            String timetable=userManService.getTimeTableFromParkAreaId(userbuildinfo.getParkareaid());
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "今天没预约");
            resultObj.put("data", timetable);

        }else{
            resultObj.put("error_code", 2);
            resultObj.put("error_msg", "今天有预约");
            resultObj.put("data", rubbishOrder);

        }
        responseData(resultObj.toString(), resp);

    }



    /**
     * 从req中读取数据
     *
     * @param req
     * @return
     */
    private String getRequestBodyString(HttpServletRequest req) {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        }
        return builder.toString();
    }

    private void responseErrorData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        JSONObject resultObj = new JSONObject();
        resultObj.put("error_code", 1);
        resultObj.put("error_msg", string);
        responseData(resultObj.toString(), resp);
    }

    private void responseData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        responseDate("application/json;charset=UTF-8", string, resp);

    }

    private void responseDate(String contentType, String value, HttpServletResponse resp) throws Exception {
        resp.setContentType(contentType);
        resp.getWriter().write(value);
    }
}
